package first.codeTop.byteDance;

/**
 * @ClassName Leetcode215
 * @description:
 * @author: 荣燊
 * @create: 2021-07-23 21:28
 **/
public class Leetcode215 {
    // 数组中的第k个最大元素
    public static void main(String[] args) {

    }

    // 试试快排
    public static int findKthLargest(int[] nums, int k) {
        return select(nums, 0, nums.length-1, nums.length-k);
    }

    public static int select(int[] a, int l, int r, int p) {
        int position = position(a, l, r);
        if (position == p) {
            return a[position];
        } else {
            return position < p ? select(a, position+1, r, p) : select(a, l, position-1, p);
        }

    }

    public static int position(int[] nums, int left, int right) {
        int i = left;
        int j = right;
        int tmp = nums[i];
        while (i < j) {
            while (i < j && nums[j] >= tmp) {
                j--;
            }
            swap(nums, i, j);
            while (i < j && nums[i] <= tmp) {
                i++;
            }
            swap(nums, i, j);
        }
        return i;
    }

    public static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
